# -*- coding:utf-8 -*-
#import celery
from celery import task
import getlottory
from models import LotteryInfo
from andy_manager import settings
#@task
def test_file():
    import time
    print '13456'
    f=open('E:/project/jdb_manager/websys/test.txt','a')    # r只读，w可写，a追加
    f.write(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))
    f.write('\n')
    f.close()

#test_file()

'''
def save_lottoryinfo(returnOBJ=0):
    import getlottory
    from models import LotteryInfo
    t_ok=0
    t_obj=getlottory.getNewKeno8()
    #print t_obj
    ll=None
    print('--lottory_grap--',t_obj)
    if t_obj and len(t_obj['ball'])>0:
     #获取数据库最新的期号
        last_item=LotteryInfo.objects.latest('id')
        last_id=None
        if last_item :
            last_id=last_item.issue
        this_id=t_obj['id']
        if last_id==None or int(this_id)>int(last_id):
            ll=LotteryInfo()#res_data={'ball':[],'extra':[],'id':'','time':''}
            ll.extra=t_obj['extra']
            ll.result=t_obj['ball']
            ll.issue=t_obj['id']
            ll.open_time=t_obj['time']
            ll.save()
            t_ok=1
            ll=LotteryInfo.objects.get(pk=ll.pk)
    else:
        print('--not out...')
    if returnOBJ:
        return ll
    return t_ok

'''
msg = 0
def save_info():
    global msg
    # from websys import getlottory
    # from websys.models import LotteryInfo
    data = getlottory.getNewKeno8()
    issue = data['id']
    print '-------------1----------------',issue
    if not issue or issue != None:
        result= data['ball']
        extra = data['extra']
        open_time = data['time']
        create_time = data['time']
        try:
            db_issue = LotteryInfo.objects.filter(issue=issue).count()
            #print issue,'-----------',db_issue
            if db_issue==0:
                print issue,result,extra,'==============',open_time,create_time
                obj = LotteryInfo(issue=issue,result=result,extra=extra,open_time=open_time,create_time=create_time)
                obj.save()
                print '=----------------------save in SQL success-------------------='
            else:
                print 'Issue aready exist in SQL...'
        except:
            print '==============SQL UNknow Error============='
    else:
        print 'data is empty'



#插入到开奖表中


def lottory_grap():
    import time
    #2秒循环一次,分钟整除5则去抓取
    print('--lottory_grap---',time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))
    t_hour_min=9
    t_hour_max=23
    t_hour=int(time.strftime('%H',time.localtime(time.time())))
    t_minute=time.strftime('%M',time.localtime(time.time()))
    if t_hour_min <= t_hour <= t_hour_max and int(t_minute)%5<2:#如果分钟整除5就保存爬取期号
            #保存
            save_info()
            print 'saving in SQL please waiting.....'
    else:
        print ' minute not Operable ,pass'



import traceback
import time
def time_task():
    runing = 1
    while runing:
        try:
            lottory_grap()
            time.sleep(6)
        except:
            traceback.print_exc()

#time_task()


import urllib2,ujson
def save_info_two():
    url = 'http://139.199.200.238/api/home'
    data = urllib2.urlopen(url, timeout=5)
    get_infos=ujson.loads(data.read())
    print get_infos,'<<<-----------url result--------'
    if get_infos['errcode'] =='0000':
        issue = int(get_infos['data']['Issue'])
        num_list=get_infos['data']['Num'].split('|')
        result=num_list[0]
        extra=num_list[1]
        open_time=get_infos['data']['PrizeTime']
        try:
            db_issue = LotteryInfo.objects.filter(issue=issue).count()
            if db_issue==0:
                obj = LotteryInfo(issue=issue,result=result,extra=extra,open_time=open_time)
                obj.save()
                print '=----------------------save in SQL success-------------------='
            else:
                print 'Issue aready exist in SQL...'
        except:
            print '==============SQL UNknow Error============='
    else:
        print 'url open error'









def lottory_grap_two():
    import time
    #2秒循环一次,分钟整除5则去抓取
    print('--lottory_grap---',time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))
    # t_hour_min=9
    # t_hour_max=23
    # t_hour=int(time.strftime('%H',time.localtime(time.time())))
    t_minute=time.strftime('%M',time.localtime(time.time()))
    if int(t_minute)%5<2:#如果分钟整除5就保存爬取期号
            #保存
            save_info_two()
            print 'saving in SQL please waiting.....'
    else:
        print ' minute not Operable ,pass'





def time_task_two():
    run = 1
    while run:
        try:
            lottory_grap_two()
            time.sleep(6)
        except:
            traceback.print_exc()




print time_task_two()
#
# def save_info2():
#     global msg
#     from websys import getlottory
#     from websys.models import LotteryInfo
#     data = getlottory.get_keno8_baidu()
#     issue = data['id']
#     if not issue or issue != None:
#         result= data['ball']
#         extra = data['extra']
#         open_time = data['time']
#         create_time = data['time']
#         try:
#             db_issue = LotteryInfo.objects.filter(issue=issue).count()
#             if db_issue==0:
#                 obj = LotteryInfo(issue=issue,result=result,extra=extra,open_time=open_time,create_time=create_time)
#                 obj.save()
#                 print '=----------------------save in SQL success-------------------='
#             else:
#                 print 'Issue aready exist in SQL...'
#         except:
#             print '==============SQL UNknow Error============='
#     else:
#         print 'data is empty'
#
#
#
# @task()
# def saveissue():
#     import time
#     # 2秒循环一次,分钟整除5则去抓取
#     print('--lottory_grap---', time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
#     t_hour_min = 9
#     t_hour_max = 23
#     t_hour = int(time.strftime('%H', time.localtime(time.time())))
#     t_minute = time.strftime('%M', time.localtime(time.time()))
#     if t_hour_min <= t_hour <= t_hour_max and int(t_minute) % 5 < 2:  # 如果分钟整除5就保存爬取期号
#             # 保存
#         save_info2()
#         print 'saving in SQL please waiting.....'
#     else:
#         print ' minute not Operable ,pass'



    # th2 = threading.Thread(target=lottory_grap)
    # th2.start()
#save_lottoryinfo()
#lottory_grap()

